//
//  XFDownloadModel.swift
//  XFDownload
//
//  Created by mac on 2018/10/27.
//  Copyright © 2018 zeroLu. All rights reserved.
//

import UIKit

enum XFDownloadState {
    case waiting
    case running
    case suspended
    case canceled
    case completed
    case failed
}

typealias XFDownloadStateBlock = ((_ url: URL?, _ state: XFDownloadState)->Void)

typealias XFDownloadProgressBlock = ((_ url: URL?, _ receivedSize: Int64, _ expectedSize: Int64, _ progress: Float)->Void)

typealias XFDownloadCompletionBlock = ((_ url: URL?, _ success: Bool, _ sandBox: String, _ error: Error?)->Void)

class XFDownloadModel: NSObject {

    var outputStream: OutputStream?
    
    var dataTask: URLSessionDataTask?
    
    var url: URL?
    
    var totalLength: Int64 = 0
    
    var destPath: String = ""
    
    var stateBlock: XFDownloadStateBlock?
    
    var progressBlock: XFDownloadProgressBlock?
    
    var completionBlock: XFDownloadCompletionBlock?
    
    func openOutputStream() {
        if let _stream = outputStream {
            _stream.open()
        }
    }
    
    func closeOutputStream() {
        
        if let _stream = outputStream {
            
            if _stream.streamStatus != Stream.Status.error {
               _stream.close()
            }
            
            outputStream = nil
        }
    }
    
    override func isEqual(_ object: Any?) -> Bool {
        guard let _model = object as? XFDownloadModel else {
            return false
        }
        
        return url == _model.url
    }
    
    override var hashValue: Int {
        return url.hashValue
    }
}
